package com.etlmaster.executor.scheduler.utils;

import java.util.concurrent.Callable;

import com.etlmaster.executor.agent.Agents;
import com.etlmaster.executor.scheduler.Proc;
import com.etlmaster.executor.scheduler.ScheduleServer;
import com.etlmaster.executor.utils.LogWriter;
import com.etlmaster.executor.utils.Shell;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class CallRunLocalCmd  implements Callable<CallableResult> {
	public int FAILURE = 1;
	public static final String SUCCESS_MSG = "success";
	public static final int SUCCESS = 0;

	private Agents agent;
	private String localCmd;

	private Proc proc;
	public CallRunLocalCmd(String cmd,Agents agent,Proc proc){
		this.localCmd=cmd;
		this.proc=proc;
		this.agent=agent;
	}
	@Override
	public CallableResult call() throws Exception {
		CallableResult result=null;

		try {
			String[] commands=localCmd.split(" ");
			Shell.ShellCommandExecutor executor= new Shell.ShellCommandExecutor(commands);
			
			executor.runCmdLog(localCmd);
			int rtnFlag=executor.getExitCode();
			
			LogWriter.addLog("INFO",executor.getOutput());
			if(rtnFlag!=0){
				LogWriter.addLog("ERROR","流程{}执行失败，退出值为：{}", proc.getProc_name(),rtnFlag+"");
				result=new CallableResult(rtnFlag, "退出值不为0,为"+rtnFlag);

			}else{
				LogWriter.addLog("INFO","流程{}执行成功", proc.getProc_name());
				result= new CallableResult(SUCCESS, SUCCESS_MSG);

			}
			
		} catch (Exception e) {			
			e.printStackTrace();
			result=new CallableResult(FAILURE, e.getMessage());
		}

		ScheduleServer.getLock().lock();
		agent.getRunningProcs().remove(proc);
		ScheduleServer.getLock().unlock();

		return result;
	}

}
